package com.fufufu.mail.product.service.impl;

import com.fufufu.common.constant.ProductConstant;
import com.fufufu.mail.product.dao.AttrAttrgroupRelationDao;
import com.fufufu.mail.product.dao.AttrGroupDao;
import com.fufufu.mail.product.dao.CategoryDao;
import com.fufufu.mail.product.entity.AttrAttrgroupRelationEntity;
import com.fufufu.mail.product.entity.AttrGroupEntity;
import com.fufufu.mail.product.entity.CategoryEntity;
import com.fufufu.mail.product.service.AttrAttrgroupRelationService;
import com.fufufu.mail.product.service.CategoryService;
import com.fufufu.mail.product.vo.AttrInfoResponeseVo;
import com.fufufu.mail.product.vo.AttrResponseVo;
import com.fufufu.mail.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fufufu.common.utils.PageUtils;
import com.fufufu.common.utils.Query;

import com.fufufu.mail.product.dao.AttrDao;
import com.fufufu.mail.product.entity.AttrEntity;
import com.fufufu.mail.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.w3c.dom.Attr;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    //TODO 这里有个大问题，到底是注入Service还是DAO？？？
    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Resource
    private AttrGroupDao attrGroupDao;

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private CategoryService categoryService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveAttr(AttrVo attrVo) {
        // 基本属性的保存
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.save(attrEntity);
        // 属性和属性组对应关系的保存
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        // 当属性是基本属性的时候才需要保存关联关系,这个里不要直接使用魔法值1，要使用常量
        if (attrVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attrVo.getAttrGroupId() != null) {
            // 这里需要返回自增id
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttr(Map<String, Object> params, Long catelogId) {
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        // 模糊查询
        if (StringUtils.hasText(key)) {
            queryWrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        // 类别查询
        if (catelogId != 0) {
            queryWrapper.and((obj) -> {
                obj.eq("catelog_id", catelogId);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        // 得到分页中的数据
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrResponseVo> responseVos = records.stream().map((attrEntity) -> {
            AttrResponseVo attrResponseVo = new AttrResponseVo();
            BeanUtils.copyProperties(attrEntity, attrResponseVo);
            // 给attrResponseVo设置分类和分组名字
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq("attr_id", attrEntity.getAttrId()));
            if (relationEntity != null) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrResponseVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrResponseVo.setCatelogName(categoryEntity.getName());
            }
            return attrResponseVo;
        }).collect(Collectors.toList());

        pageUtils.setList(responseVos);
        return pageUtils;
    }

    @Override
    public AttrInfoResponeseVo getInfo(Long attrId) {
        // 先查到本身
        AttrEntity byId = this.getById(attrId);
        AttrInfoResponeseVo attrInfoResponeseVo = new AttrInfoResponeseVo();
        BeanUtils.copyProperties(byId, attrInfoResponeseVo);
        AttrAttrgroupRelationEntity attrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(
                new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attrId));
        // 非空判断
        if (attrgroupRelationEntity != null) {
            attrInfoResponeseVo.setAttrGroupId(attrgroupRelationEntity.getAttrGroupId());
        }
        attrInfoResponeseVo.setCatelogPath(categoryService.findCatelogPath(attrInfoResponeseVo.getCatelogId()));
        return attrInfoResponeseVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateAttrVoById(AttrVo attr) {
        // 先保存entity的基本信息,也就是自己的信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        // 只有基本属性才需要和属性分组对应
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 修改属性和属性组对应表的关系，需要强调的是一个基本属性只会属于一个分组，所以这里可以用属性id进行分组的更新
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity,
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }
    }

    @Override
    public PageUtils querySaleAttr(Map<String, Object> params, Long catelogId) {
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        // 模糊查询
        if (StringUtils.hasText(key)) {
            queryWrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        // 类别查询
        if (catelogId != 0) {
            queryWrapper.and((obj) -> {
                obj.eq("catelog_id", catelogId);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );



        PageUtils pageUtils = new PageUtils(page);
        // list是有数据的
        List<AttrEntity> records = page.getRecords();
        List<AttrResponseVo> responseVos = records.stream().map((attrEntity) -> {
            System.out.println(attrEntity);
            AttrResponseVo attrResponseVo = new AttrResponseVo();
            BeanUtils.copyProperties(attrEntity, attrResponseVo);
            // 给attrResponseVo设置分类和分组名字
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrResponseVo.setCatelogName(categoryEntity.getName());
            }
            return attrResponseVo;
        }).collect(Collectors.toList());
        pageUtils.setList(responseVos);
        return pageUtils;
    }

    /**
     * 根据分组id查找所有关联的属性
     * @param attrgroupId 分组id
     * @return
     */
    @Override
    public List<AttrEntity> getAttrByAttrgroupId(Long attrgroupId) {
        // 先在中间表中查出当前attrgroupId对应的所有attrid
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        // 在attr表中查出所有需要的attr
        // 这里要进行非空判断,因为当前attrgroupId没有基本属性
        if (attrIds == null || attrIds.size() == 0) {
            return null;
        }
        return this.listByIds(attrIds);
    }

    @Override
    public List<AttrEntity> getAttrByAttrgroupIds(List<Long> groupIds) {
        if (groupIds.size() == 0) {
            return null;
        }
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        List<Long> attrIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        if (attrIds.size() == 0) {
            return null;
        }
        return this.listByIds(attrIds);
    }

    /**
     * 查询出当前组id可关联的基本属性
     */
    @Override
    public PageUtils getNoAttrByAttrgroupId(Long attrgroupId, Map<String, Object> params) {
        // 先查出当前组属于哪个分类
        Long catelogId = attrGroupDao.selectById(attrgroupId).getCatelogId();
        // 查出这个分类有哪些属性分组
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
        List<Long> groupIds = attrGroupEntities.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
        // 查出其属性分组关联的属性关系
        List<AttrAttrgroupRelationEntity> noNeedRelation = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        // 通过上面获得的属性关系，可以查出当前类别下已经关联了的属性的id
        List<Long> noNeedAttrId = noNeedRelation.stream()
                .map(AttrAttrgroupRelationEntity::getAttrId)
                .collect(Collectors.toList());
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                // 分组只关联基本属性，不关联销售属性
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        // 一定要注意，in或者noin一定要保证集合有元素
        if (noNeedAttrId.size() != 0) {
            wrapper.notIn("attr_id", noNeedAttrId);
        }
        // 模糊查询
        String key = (String)params.get("key");
        if (StringUtils.hasText(key)) {
            wrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        // 获取分页
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

}